<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-7xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">Canvas API</h1>
        <p class="text-gray-300 text-lg">
          2D 图形绘制和动画，支持图像处理、数据可视化和游戏开发
        </p>
      </div>

      <!-- 基础绘图 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">基础绘图</h2>
        
        <div class="bg-gray-800 rounded-lg p-6 mb-6">
          <canvas
            ref="basicCanvasRef"
            width="800"
            height="400"
            class="border border-gray-700 rounded-lg bg-white w-full max-w-full mx-auto block"
          ></canvas>
          
          <div class="flex flex-wrap gap-3 mt-4 justify-center">
            <button @click="drawShapes" class="tech-button">
              <i class="i-carbon-shape-join mr-2"></i>
              绘制图形
            </button>
            <button @click="drawGradients" class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-3 rounded-lg transition-colors">
              <i class="i-carbon-color-palette mr-2"></i>
              渐变效果
            </button>
            <button @click="drawText" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-colors">
              <i class="i-carbon-text-font mr-2"></i>
              绘制文字
            </button>
            <button @click="drawPatterns" class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg transition-colors">
              <i class="i-carbon-grid mr-2"></i>
              图案填充
            </button>
            <button @click="clearCanvas('basic')" class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors">
              <i class="i-carbon-clean mr-2"></i>
              清空画布
            </button>
          </div>
        </div>
      </div>

      <!-- 动画演示 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">动画演示</h2>
        
        <div class="bg-gray-800 rounded-lg p-6 mb-6">
          <canvas
            ref="animationCanvasRef"
            width="800"
            height="400"
            class="border border-gray-700 rounded-lg bg-gray-900 w-full max-w-full mx-auto block"
          ></canvas>
          
          <div class="flex flex-wrap gap-3 mt-4 justify-center">
            <button @click="startBouncingBall" class="tech-button">
              <i class="i-carbon-play-filled mr-2"></i>
              弹跳球动画
            </button>
            <button @click="startParticles" class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-3 rounded-lg transition-colors">
              <i class="i-carbon-rain-drop mr-2"></i>
              粒子效果
            </button>
            <button @click="startClockAnimation" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-colors">
              <i class="i-carbon-time mr-2"></i>
              时钟动画
            </button>
            <button @click="stopAnimation" class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors">
              <i class="i-carbon-stop-filled mr-2"></i>
              停止动画
            </button>
          </div>
        </div>
      </div>

      <!-- 交互式绘图 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">交互式绘图</h2>
        
        <div class="bg-gray-800 rounded-lg p-6 mb-6">
          <div class="mb-4 flex flex-wrap gap-4 items-center">
            <div>
              <label class="text-white mr-2">画笔颜色:</label>
              <input
                v-model="brushColor"
                type="color"
                class="w-12 h-10 rounded cursor-pointer"
              >
            </div>
            <div>
              <label class="text-white mr-2">画笔大小: {{ brushSize }}</label>
              <input
                v-model.number="brushSize"
                type="range"
                min="1"
                max="50"
                class="w-32"
              >
            </div>
            <button @click="clearCanvas('interactive')" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded transition-colors">
              <i class="i-carbon-clean mr-2"></i>
              清空
            </button>
            <button @click="saveCanvasImage" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded transition-colors">
              <i class="i-carbon-download mr-2"></i>
              保存图片
            </button>
          </div>
          
          <canvas
            ref="interactiveCanvasRef"
            @mousedown="startDrawing"
            @mousemove="draw"
            @mouseup="stopDrawing"
            @mouseleave="stopDrawing"
            @touchstart.prevent="startDrawingTouch"
            @touchmove.prevent="drawTouch"
            @touchend.prevent="stopDrawing"
            class="border border-gray-700 rounded-lg bg-white w-full max-w-full mx-auto block cursor-crosshair"
            style="width: 800px; height: 400px; max-width: 100%;"
          ></canvas>
          
          <p class="text-gray-400 text-sm mt-3 text-center">
            在画布上拖动鼠标或触摸来绘画
          </p>
        </div>
      </div>

      <!-- 图像处理 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">图像处理</h2>
        
        <div class="bg-gray-800 rounded-lg p-6">
          <div class="mb-4">
            <input
              ref="imageInputRef"
              type="file"
              accept="image/*"
              @change="loadImage"
              class="hidden"
            >
            <button
              @click="imageInputRef?.click()"
              class="tech-button"
            >
              <i class="i-carbon-image mr-2"></i>
              加载图片
            </button>
          </div>
          
          <canvas
            ref="imageCanvasRef"
            width="800"
            height="400"
            class="border border-gray-700 rounded-lg bg-gray-900 w-full max-w-full mx-auto block mb-4"
          ></canvas>
          
          <div v-if="hasLoadedImage" class="flex flex-wrap gap-3 justify-center">
            <button @click="applyFilter('grayscale')" class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded transition-colors">
              灰度
            </button>
            <button @click="applyFilter('sepia')" class="bg-amber-600 hover:bg-amber-700 text-white px-4 py-2 rounded transition-colors">
              复古
            </button>
            <button @click="applyFilter('invert')" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded transition-colors">
              反色
            </button>
            <button @click="applyFilter('brightness')" class="bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-2 rounded transition-colors">
              增亮
            </button>
            <button @click="applyFilter('blur')" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded transition-colors">
              模糊
            </button>
            <button @click="resetImage" class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded transition-colors">
              重置
            </button>
          </div>
        </div>
      </div>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">核心 API</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">getContext('2d')</code> - 获取2D绘图上下文</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">fillRect()</code> - 绘制填充矩形</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">strokeRect()</code> - 绘制矩形边框</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">arc()</code> - 绘制圆弧</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">beginPath()</code> - 开始新路径</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">moveTo() / lineTo()</code> - 移动/绘制线条</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">drawImage()</code> - 绘制图像</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">getImageData()</code> - 获取像素数据</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>图表和数据可视化</li>
              <li>游戏开发</li>
              <li>图像编辑器</li>
              <li>动画和特效</li>
              <li>签名板</li>
              <li>绘图应用</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// Canvas 引用
const basicCanvasRef = ref<HTMLCanvasElement>()
const animationCanvasRef = ref<HTMLCanvasElement>()
const interactiveCanvasRef = ref<HTMLCanvasElement>()
const imageCanvasRef = ref<HTMLCanvasElement>()
const imageInputRef = ref<HTMLInputElement>()

// 交互式绘图状态
const isDrawing = ref(false)
const brushColor = ref('#3b82f6')
const brushSize = ref(5)

// 动画状态
let animationId: number | null = null

// 图像处理状态
const hasLoadedImage = ref(false)
let originalImageData: ImageData | null = null

// 初始化高 DPI 画布
const setupHighDPICanvas = (canvas: HTMLCanvasElement, width: number, height: number) => {
  const dpr = window.devicePixelRatio || 1
  
  // 设置实际像素大小（考虑设备像素比）
  canvas.width = width * dpr
  canvas.height = height * dpr
  
  // 设置显示大小
  canvas.style.width = width + 'px'
  canvas.style.height = height + 'px'
  
  // 缩放绘图上下文以匹配设备像素比
  const ctx = canvas.getContext('2d')
  if (ctx) {
    ctx.scale(dpr, dpr)
  }
  
  return dpr
}

// 初始化
onMounted(() => {
  // 初始化交互式画布为高 DPI
  if (interactiveCanvasRef.value) {
    setupHighDPICanvas(interactiveCanvasRef.value, 800, 400)
  }
  
  drawShapes()
})

// 清理
onUnmounted(() => {
  stopAnimation()
})

// === 基础绘图功能 ===

const drawShapes = () => {
  const canvas = basicCanvasRef.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  // 绘制矩形
  ctx.fillStyle = '#3b82f6'
  ctx.fillRect(50, 50, 150, 100)
  
  // 绘制带边框的矩形
  ctx.strokeStyle = '#ef4444'
  ctx.lineWidth = 3
  ctx.strokeRect(250, 50, 150, 100)
  
  // 绘制圆形
  ctx.beginPath()
  ctx.arc(525, 100, 50, 0, 2 * Math.PI)
  ctx.fillStyle = '#10b981'
  ctx.fill()
  
  // 绘制三角形
  ctx.beginPath()
  ctx.moveTo(650, 50)
  ctx.lineTo(750, 50)
  ctx.lineTo(700, 150)
  ctx.closePath()
  ctx.fillStyle = '#f59e0b'
  ctx.fill()
  
  // 绘制线条
  ctx.beginPath()
  ctx.moveTo(50, 200)
  ctx.lineTo(200, 300)
  ctx.lineTo(350, 200)
  ctx.strokeStyle = '#8b5cf6'
  ctx.lineWidth = 5
  ctx.stroke()
  
  // 绘制贝塞尔曲线
  ctx.beginPath()
  ctx.moveTo(400, 250)
  ctx.bezierCurveTo(450, 200, 550, 300, 600, 250)
  ctx.strokeStyle = '#ec4899'
  ctx.lineWidth = 3
  ctx.stroke()
}

const drawGradients = () => {
  const canvas = basicCanvasRef.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  // 线性渐变
  const linearGradient = ctx.createLinearGradient(50, 50, 300, 200)
  linearGradient.addColorStop(0, '#3b82f6')
  linearGradient.addColorStop(0.5, '#8b5cf6')
  linearGradient.addColorStop(1, '#ec4899')
  
  ctx.fillStyle = linearGradient
  ctx.fillRect(50, 50, 250, 150)
  
  // 径向渐变
  const radialGradient = ctx.createRadialGradient(500, 125, 20, 500, 125, 100)
  radialGradient.addColorStop(0, '#fef08a')
  radialGradient.addColorStop(0.5, '#f59e0b')
  radialGradient.addColorStop(1, '#ef4444')
  
  ctx.fillStyle = radialGradient
  ctx.fillRect(400, 25, 200, 200)
  
  // 圆锥渐变（如果支持）
  ctx.fillStyle = '#10b981'
  ctx.fillRect(50, 250, 700, 100)
  
  ctx.fillStyle = '#ffffff'
  ctx.font = 'bold 20px Arial'
  ctx.fillText('线性渐变', 125, 135)
  ctx.fillText('径向渐变', 450, 135)
}

const drawText = () => {
  const canvas = basicCanvasRef.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  // 不同字体
  ctx.fillStyle = '#3b82f6'
  ctx.font = '30px Arial'
  ctx.fillText('Arial 字体', 50, 50)
  
  ctx.fillStyle = '#10b981'
  ctx.font = 'bold 40px Georgia'
  ctx.fillText('粗体 Georgia', 50, 120)
  
  ctx.fillStyle = '#f59e0b'
  ctx.font = 'italic 35px Times New Roman'
  ctx.fillText('斜体 Times', 50, 190)
  
  // 描边文字
  ctx.strokeStyle = '#ef4444'
  ctx.lineWidth = 2
  ctx.font = 'bold 45px Arial'
  ctx.strokeText('描边文字', 50, 260)
  
  // 文字阴影
  ctx.shadowColor = '#8b5cf6'
  ctx.shadowBlur = 10
  ctx.shadowOffsetX = 5
  ctx.shadowOffsetY = 5
  ctx.fillStyle = '#ec4899'
  ctx.font = 'bold 40px Arial'
  ctx.fillText('阴影效果', 50, 330)
}

const drawPatterns = () => {
  const canvas = basicCanvasRef.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  // 创建图案画布
  const patternCanvas = document.createElement('canvas')
  patternCanvas.width = 20
  patternCanvas.height = 20
  const patternCtx = patternCanvas.getContext('2d')
  
  if (patternCtx) {
    // 绘制图案
    patternCtx.fillStyle = '#3b82f6'
    patternCtx.fillRect(0, 0, 10, 10)
    patternCtx.fillRect(10, 10, 10, 10)
    patternCtx.fillStyle = '#10b981'
    patternCtx.fillRect(10, 0, 10, 10)
    patternCtx.fillRect(0, 10, 10, 10)
    
    const pattern = ctx.createPattern(patternCanvas, 'repeat')
    if (pattern) {
      ctx.fillStyle = pattern
      ctx.fillRect(50, 50, 300, 300)
    }
  }
  
  // 点状图案
  const dotPattern = document.createElement('canvas')
  dotPattern.width = 20
  dotPattern.height = 20
  const dotCtx = dotPattern.getContext('2d')
  
  if (dotCtx) {
    dotCtx.fillStyle = '#f59e0b'
    dotCtx.beginPath()
    dotCtx.arc(10, 10, 3, 0, 2 * Math.PI)
    dotCtx.fill()
    
    const pattern = ctx.createPattern(dotPattern, 'repeat')
    if (pattern) {
      ctx.fillStyle = pattern
      ctx.fillRect(400, 50, 350, 300)
    }
  }
}

// === 动画功能 ===

const startBouncingBall = () => {
  stopAnimation()
  
  const canvas = animationCanvasRef.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  let x = canvas.width / 2
  let y = 50
  let dx = 3
  let dy = 2
  const radius = 20

  const animate = () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    
    // 绘制球
    ctx.beginPath()
    ctx.arc(x, y, radius, 0, 2 * Math.PI)
    const gradient = ctx.createRadialGradient(x - 5, y - 5, 5, x, y, radius)
    gradient.addColorStop(0, '#ffffff')
    gradient.addColorStop(1, '#3b82f6')
    ctx.fillStyle = gradient
    ctx.fill()
    
    // 更新位置
    x += dx
    y += dy
    
    // 碰撞检测
    if (x + radius > canvas.width || x - radius < 0) dx = -dx
    if (y + radius > canvas.height || y - radius < 0) dy = -dy
    
    animationId = requestAnimationFrame(animate)
  }
  
  animate()
}

const startParticles = () => {
  stopAnimation()
  
  const canvas = animationCanvasRef.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  interface Particle {
    x: number
    y: number
    vx: number
    vy: number
    radius: number
    color: string
  }

  const particles: Particle[] = []
  const particleCount = 50
  
  // 创建粒子
  for (let i = 0; i < particleCount; i++) {
    particles.push({
      x: Math.random() * canvas.width,
      y: Math.random() * canvas.height,
      vx: (Math.random() - 0.5) * 3,
      vy: (Math.random() - 0.5) * 3,
      radius: Math.random() * 5 + 2,
      color: `hsl(${Math.random() * 360}, 70%, 60%)`
    })
  }

  const animate = () => {
    ctx.fillStyle = 'rgba(17, 24, 39, 0.1)'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    
    particles.forEach(particle => {
      // 绘制粒子
      ctx.beginPath()
      ctx.arc(particle.x, particle.y, particle.radius, 0, 2 * Math.PI)
      ctx.fillStyle = particle.color
      ctx.fill()
      
      // 更新位置
      particle.x += particle.vx
      particle.y += particle.vy
      
      // 边界反弹
      if (particle.x < 0 || particle.x > canvas.width) particle.vx *= -1
      if (particle.y < 0 || particle.y > canvas.height) particle.vy *= -1
    })
    
    animationId = requestAnimationFrame(animate)
  }
  
  animate()
}

const startClockAnimation = () => {
  stopAnimation()
  
  const canvas = animationCanvasRef.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  const centerX = canvas.width / 2
  const centerY = canvas.height / 2
  const radius = 150

  const animate = () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    
    const now = new Date()
    const hours = now.getHours() % 12
    const minutes = now.getMinutes()
    const seconds = now.getSeconds()
    
    // 绘制表盘
    ctx.beginPath()
    ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI)
    ctx.fillStyle = '#ffffff'
    ctx.fill()
    ctx.strokeStyle = '#1f2937'
    ctx.lineWidth = 3
    ctx.stroke()
    
    // 绘制刻度
    for (let i = 0; i < 12; i++) {
      const angle = (i * Math.PI) / 6
      const x1 = centerX + Math.cos(angle - Math.PI / 2) * (radius - 20)
      const y1 = centerY + Math.sin(angle - Math.PI / 2) * (radius - 20)
      const x2 = centerX + Math.cos(angle - Math.PI / 2) * (radius - 10)
      const y2 = centerY + Math.sin(angle - Math.PI / 2) * (radius - 10)
      
      ctx.beginPath()
      ctx.moveTo(x1, y1)
      ctx.lineTo(x2, y2)
      ctx.strokeStyle = '#1f2937'
      ctx.lineWidth = 3
      ctx.stroke()
    }
    
    // 时针
    const hourAngle = ((hours + minutes / 60) * Math.PI) / 6
    ctx.beginPath()
    ctx.moveTo(centerX, centerY)
    ctx.lineTo(
      centerX + Math.cos(hourAngle - Math.PI / 2) * (radius * 0.5),
      centerY + Math.sin(hourAngle - Math.PI / 2) * (radius * 0.5)
    )
    ctx.strokeStyle = '#1f2937'
    ctx.lineWidth = 6
    ctx.stroke()
    
    // 分针
    const minuteAngle = ((minutes + seconds / 60) * Math.PI) / 30
    ctx.beginPath()
    ctx.moveTo(centerX, centerY)
    ctx.lineTo(
      centerX + Math.cos(minuteAngle - Math.PI / 2) * (radius * 0.7),
      centerY + Math.sin(minuteAngle - Math.PI / 2) * (radius * 0.7)
    )
    ctx.strokeStyle = '#3b82f6'
    ctx.lineWidth = 4
    ctx.stroke()
    
    // 秒针
    const secondAngle = (seconds * Math.PI) / 30
    ctx.beginPath()
    ctx.moveTo(centerX, centerY)
    ctx.lineTo(
      centerX + Math.cos(secondAngle - Math.PI / 2) * (radius * 0.85),
      centerY + Math.sin(secondAngle - Math.PI / 2) * (radius * 0.85)
    )
    ctx.strokeStyle = '#ef4444'
    ctx.lineWidth = 2
    ctx.stroke()
    
    // 中心点
    ctx.beginPath()
    ctx.arc(centerX, centerY, 8, 0, 2 * Math.PI)
    ctx.fillStyle = '#1f2937'
    ctx.fill()
    
    animationId = requestAnimationFrame(animate)
  }
  
  animate()
}

const stopAnimation = () => {
  if (animationId !== null) {
    cancelAnimationFrame(animationId)
    animationId = null
  }
}

// === 交互式绘图 ===

// 获取画布坐标（考虑显示尺寸）
const getCanvasCoordinates = (canvas: HTMLCanvasElement, clientX: number, clientY: number) => {
  const rect = canvas.getBoundingClientRect()
  
  // 因为我们已经通过 ctx.scale() 处理了 DPR，这里只需要转换显示坐标
  return {
    x: clientX - rect.left,
    y: clientY - rect.top
  }
}

const startDrawing = (e: MouseEvent) => {
  isDrawing.value = true
  const canvas = interactiveCanvasRef.value
  if (!canvas) return
  
  const coords = getCanvasCoordinates(canvas, e.clientX, e.clientY)
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  ctx.beginPath()
  ctx.moveTo(coords.x, coords.y)
}

const draw = (e: MouseEvent) => {
  if (!isDrawing.value) return
  
  const canvas = interactiveCanvasRef.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  const coords = getCanvasCoordinates(canvas, e.clientX, e.clientY)
  
  ctx.lineTo(coords.x, coords.y)
  ctx.strokeStyle = brushColor.value
  ctx.lineWidth = brushSize.value
  ctx.lineCap = 'round'
  ctx.lineJoin = 'round'
  ctx.stroke()
}

const startDrawingTouch = (e: TouchEvent) => {
  isDrawing.value = true
  const canvas = interactiveCanvasRef.value
  if (!canvas) return
  
  const touch = e.touches[0]
  const coords = getCanvasCoordinates(canvas, touch.clientX, touch.clientY)
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  ctx.beginPath()
  ctx.moveTo(coords.x, coords.y)
}

const drawTouch = (e: TouchEvent) => {
  if (!isDrawing.value) return
  
  const canvas = interactiveCanvasRef.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  const touch = e.touches[0]
  const coords = getCanvasCoordinates(canvas, touch.clientX, touch.clientY)
  
  ctx.lineTo(coords.x, coords.y)
  ctx.strokeStyle = brushColor.value
  ctx.lineWidth = brushSize.value
  ctx.lineCap = 'round'
  ctx.lineJoin = 'round'
  ctx.stroke()
}

const stopDrawing = () => {
  isDrawing.value = false
}

const saveCanvasImage = () => {
  const canvas = interactiveCanvasRef.value
  if (!canvas) return
  
  const link = document.createElement('a')
  link.download = 'canvas-drawing.png'
  link.href = canvas.toDataURL()
  link.click()
}

// === 图像处理 ===

const loadImage = (e: Event) => {
  const target = e.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return
  
  const reader = new FileReader()
  reader.onload = (event) => {
    const img = new Image()
    img.onload = () => {
      const canvas = imageCanvasRef.value
      if (!canvas) return
      
      const ctx = canvas.getContext('2d')
      if (!ctx) return
      
      // 调整图片大小以适应画布
      const scale = Math.min(canvas.width / img.width, canvas.height / img.height)
      const x = (canvas.width - img.width * scale) / 2
      const y = (canvas.height - img.height * scale) / 2
      
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(img, x, y, img.width * scale, img.height * scale)
      
      // 保存原始图像数据
      originalImageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
      hasLoadedImage.value = true
    }
    img.src = event.target?.result as string
  }
  reader.readAsDataURL(file)
}

const applyFilter = (filterType: string) => {
  const canvas = imageCanvasRef.value
  if (!canvas || !originalImageData) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  ctx.putImageData(originalImageData, 0, 0)
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
  const data = imageData.data
  
  switch (filterType) {
    case 'grayscale':
      for (let i = 0; i < data.length; i += 4) {
        const avg = (data[i] + data[i + 1] + data[i + 2]) / 3
        data[i] = avg
        data[i + 1] = avg
        data[i + 2] = avg
      }
      break
      
    case 'sepia':
      for (let i = 0; i < data.length; i += 4) {
        const r = data[i]
        const g = data[i + 1]
        const b = data[i + 2]
        data[i] = Math.min(255, r * 0.393 + g * 0.769 + b * 0.189)
        data[i + 1] = Math.min(255, r * 0.349 + g * 0.686 + b * 0.168)
        data[i + 2] = Math.min(255, r * 0.272 + g * 0.534 + b * 0.131)
      }
      break
      
    case 'invert':
      for (let i = 0; i < data.length; i += 4) {
        data[i] = 255 - data[i]
        data[i + 1] = 255 - data[i + 1]
        data[i + 2] = 255 - data[i + 2]
      }
      break
      
    case 'brightness':
      for (let i = 0; i < data.length; i += 4) {
        data[i] = Math.min(255, data[i] * 1.5)
        data[i + 1] = Math.min(255, data[i + 1] * 1.5)
        data[i + 2] = Math.min(255, data[i + 2] * 1.5)
      }
      break
      
    case 'blur':
      // 简单的模糊效果（盒式模糊）
      const tempData = new Uint8ClampedArray(data)
      const width = canvas.width
      for (let y = 1; y < canvas.height - 1; y++) {
        for (let x = 1; x < width - 1; x++) {
          for (let c = 0; c < 3; c++) {
            const idx = (y * width + x) * 4 + c
            let sum = 0
            for (let ky = -1; ky <= 1; ky++) {
              for (let kx = -1; kx <= 1; kx++) {
                sum += tempData[((y + ky) * width + (x + kx)) * 4 + c]
              }
            }
            data[idx] = sum / 9
          }
        }
      }
      break
  }
  
  ctx.putImageData(imageData, 0, 0)
}

const resetImage = () => {
  const canvas = imageCanvasRef.value
  if (!canvas || !originalImageData) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  ctx.putImageData(originalImageData, 0, 0)
}

// === 清空画布 ===

const clearCanvas = (type: string) => {
  let canvas: HTMLCanvasElement | undefined
  
  switch (type) {
    case 'basic':
      canvas = basicCanvasRef.value
      break
    case 'animation':
      canvas = animationCanvasRef.value
      stopAnimation()
      break
    case 'interactive':
      canvas = interactiveCanvasRef.value
      break
  }
  
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  ctx.clearRect(0, 0, canvas.width, canvas.height)
}
</script>

<style scoped>
input[type="range"] {
  -webkit-appearance: none;
  appearance: none;
  background: transparent;
  cursor: pointer;
}

input[type="range"]::-webkit-slider-track {
  background: #374151;
  height: 0.5rem;
  border-radius: 0.25rem;
}

input[type="range"]::-moz-range-track {
  background: #374151;
  height: 0.5rem;
  border-radius: 0.25rem;
}

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 1.25rem;
  height: 1.25rem;
  border-radius: 50%;
  background: #3b82f6;
  cursor: pointer;
  margin-top: -0.375rem;
}

input[type="range"]::-moz-range-thumb {
  width: 1.25rem;
  height: 1.25rem;
  border-radius: 50%;
  background: #3b82f6;
  cursor: pointer;
  border: none;
}
</style>
